<script setup lang="ts">
  import { ref, h } from 'vue'
  import { ElDivider, TableInstance } from 'element-plus'
  import { Search, Delete, Warning, ArrowDown, CircleCheck } from '@element-plus/icons-vue'
  import {
    ElMessageBox,
    ElInput,
    ElDropdown,
    ElDropdownMenu,
    ElDropdownItem,
    ElTable,
    ElTableColumn,
    ElIcon,
    ElSpace,
  } from 'element-plus'
  import Pagination from '@/components/Pagination/index.vue'
  import defaultImage from '@/assets/image/default.png'
  import {
    useGetVideoList,
    useVideoDelByIds,
    useVideoEnableByIds,
    useVideoDisableByIds,
  } from '@/services/pages/know/useVideo'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import VideoPreviewModal from './Preview.vue'
  import VideoFormModal from './FormModal.vue'

  const { listTotal, videoList, getListParam, getListLoading, getList } = useGetVideoList()
  const { del } = useVideoDelByIds()
  const { enable } = useVideoEnableByIds()
  const { disable } = useVideoDisableByIds()

  defineOptions({
    name: 'OnLineVideo',
  })

  // 分页组件实例
  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)

  // 表格组件实例
  const tableInstance = ref<TableInstance | null>(null)

  // 视频选择id集合
  const videoSelectIds = ref<Array<string>>([])

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  // 正在查看的视频的id
  const viewingVideoId = ref('')

  // 视频预览弹窗显示状态
  const videoPreviewModalVisible = ref(false)

  // 视频表单弹窗显示状态
  const videoFormModalVisible = ref(false)

  // 编辑的视频id
  const updatingVideoId = ref('')

  /**
   * 获取列表
   */
  const _getList = () => {
    if (paginationInstance.value) {
      getListParam.value.limit = paginationInstance.value.size
      getListParam.value.page = paginationInstance.value.current
      getList()
    }
  }

  /**
   * 表格删除按钮点击事件
   * @param {OnLineVideo} video - 视频对象
   */
  const handleListDelBtnClick = (video: OnLineVideo) => {
    if (tableInstance.value) {
      tableInstance.value.clearSelection()
      tableInstance.value.toggleRowSelection(video)
      ElMessageBox({
        title: '提示',
        type: 'error',
        showCancelButton: true,
        autofocus: false,
        message: '确定删除该视频？',
        async beforeClose(action, instance, done) {
          if (['close', 'cancel'].includes(action)) {
            done()
            return
          }

          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.cancelButtonLoading = true
            const res = await del(videoSelectIds.value)
            instance.confirmButtonLoading = false
            instance.cancelButtonLoading = false
            if (res.code === 20000) {
              HMessage.success('删除成功')
              _getList()
              done()
              return
            }
            HMessageBox.error(res.message)
          }
        },
      })
    }
  }

  /**
   * 视频选择事件
   * @param {Array<OnLineVideo>} videoList - 视频列表
   */
  const handleVideoSelect = (videoList: Array<OnLineVideo>) => {
    videoSelectIds.value = videoList.map((video) => video.id)
  }

  /**
   * 批量操作事件
   * @param {('disable'|'enable'|'del')} type - 操作类型
   */
  const handleMultipleOperate = (type: 'disable' | 'enable' | 'del') => {
    ElMessageBox({
      title: '提示',
      type: type === 'del' ? 'error' : 'warning',
      autofocus: false,
      showCancelButton: true,
      message: getMultipleOperateElMessageBoxMessage(type),
      async beforeClose(action, instance, done) {
        if (['close', 'cancel'].includes(action)) {
          done()
          return
        }

        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.cancelButtonLoading = true
          const res = await multipleOperateFnCall(type)
          instance.confirmButtonLoading = false
          instance.cancelButtonLoading = false
          if (res.code === 20000) {
            HMessage.success(type === 'del' ? '删除成功' : '更新成功')
            _getList()
            done()
            return
          }
          HMessageBox.error(res.message)
        }
      },
    })
  }

  /**
   * 获取批量操作的提示
   * @param {('disable'|'enable'|'del')} type - 操作类型
   */
  const getMultipleOperateElMessageBoxMessage = (type: 'disable' | 'enable' | 'del') => {
    if (type === 'del') {
      return '确定删除选中的视频'
    }

    if (type === 'disable') {
      return '确定禁用选中的视频'
    }

    if (type === 'enable') {
      return '确定启用选中的视频'
    }
  }

  /**
   * 批量操作调用
   * @param {('disable'|'enable'|'del')} type - 操作类型
   */
  const multipleOperateFnCall = async (type: 'disable' | 'enable' | 'del') => {
    if (type === 'del') {
      return await del(videoSelectIds.value)
    }

    if (type === 'enable') {
      return await enable(videoSelectIds.value)
    }

    if (type === 'disable') {
      return await disable(videoSelectIds.value)
    }
  }

  /**
   * 预览事件
   * @param {String} id - 视频id
   */
  const handlePreview = (id: string) => {
    viewingVideoId.value = id
    videoPreviewModalVisible.value = true
  }

  /**
   * 编辑事件
   * @param {String} id - 视频id
   */
  const handleUpdate = (id: string) => {
    updatingVideoId.value = id
    videoFormModalVisible.value = true
  }

  defineExpose({ getList: _getList })
</script>

<template>
  <div v-loading="getListLoading" class="video_card" element-loading-text="加载中...">
    <div class="header">
      <div class="btn_group">
        <HPlainButton v-permission="'know_videoAdd'"  @click="videoFormModalVisible = true"> 添加视频 </HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="videoSelectIds.length <= 0">
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <div v-permission="'know_videoEnabled'">
                <el-dropdown-item @click="handleMultipleOperate('enable')">
                  <el-icon>
                    <CircleCheck />
                  </el-icon>
                  批量启用
                </el-dropdown-item>
              </div>
              <div v-permission="'know_videoDisabled'">
                <el-dropdown-item @click="handleMultipleOperate('disable')">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              </div>
              <div v-permission="'know_videoDelete'">
                <el-dropdown-item @click="handleMultipleOperate('del')">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
              </div>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search">
        <el-input
          v-model.trim="getListParam.name"
          clearable
          placeholder="请输入关键字"
          @keyup.enter="_getList"
          @clear="_getList"
        />
        <HButton type="primary" @click="_getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>

    <!-- 表格内容 -->
    <div class="table">
      <el-table
        ref="tableInstance"
        :border="true"
        stripe
        resizable
        :data="videoList"
        height="100%"
        :tooltip-options="{
          popperClass: 'table-tooltip',
        }"
        @selection-change="handleVideoSelect"
      >
        <!-- 选择 -->
        <el-table-column type="selection" width="50" fixed="left" :align="'center'" />

        <!-- 序号 -->
        <el-table-column type="index" label="序号" width="55" fixed="left" :align="'center'" />

        <!-- 视频名称 -->
        <el-table-column
          show-overflow-tooltip
          prop="name"
          label="视频名称"
          width="100"
        ></el-table-column>

        <!-- 视频封面 -->
        <el-table-column prop="image" label="视频封面" width="100">
          <template #default="scope">
            <h-image
              :src="scope.row.image || defaultImage"
              :width="40"
              :height="25"
              :show-del-btn="false"
              :padding="1"
              :show-mask="!!scope.row.image"
            />
          </template>
        </el-table-column>

        <!-- 关联产品 -->
        <el-table-column
          show-overflow-tooltip
          prop="knowledgeType"
          label="关联产品"
          min-width="230"
        >
          <template #default="{ row }">
            {{ row.goods.join('、') }}
          </template>
        </el-table-column>

        <!-- 点击数 -->
        <el-table-column prop="clickNum" label="点击数" width="70" />

        <!-- 可见类型 -->
        <el-table-column prop="visibilityType" label="可见类型" width="80">
          <template #default="{ row }">
            {{
              row.visibilityType === 1
                ? '全部可见'
                : row.visibilityType === 2
                ? '网点可见'
                : '公司可见'
            }}
          </template>
        </el-table-column>

        <!-- 创建时间 -->
        <el-table-column prop="createTime" label="创建时间" width="150" />

        <!-- 更新时间 -->
        <el-table-column prop="updateTime" label="更新时间" width="150" />

        <!-- 状态 -->
        <el-table-column prop="status" label="状态" width="80" :align="'center'" fixed="right">
          <template #default="scope">
            <div class="flex_justify_center">
              <HStatus v-if="scope.row.status === false">启用</HStatus>
              <HStatus v-if="scope.row.status === true" type="info">禁用</HStatus>
            </div>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column fixed="right" label="操作" width="140">
          <template #default="scope">
            <el-space :size="0" :spacer="spacer">
              <HLink v-permission="'know_videoPreview'" @click="handlePreview(scope.row.id)">预览</HLink>
              <HLink v-permission="'know_videoUpdate'" @click="handleUpdate(scope.row.id)">编辑</HLink>
              <h-link v-permission="'know_videoDelete'" type="error" @click="handleListDelBtnClick(scope.row)">删除</h-link>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <Pagination
        ref="paginationInstance"
        :list_total="listTotal"
        @size-change="_getList"
        @current-change="_getList"
      />
    </div>

    <video-preview-modal
      v-model:visible="videoPreviewModalVisible"
      :video-id="viewingVideoId"
    ></video-preview-modal>

    <video-form-modal
      v-model:visible="videoFormModalVisible"
      :video-id="updatingVideoId"
      @update="_getList"
    ></video-form-modal>
  </div>
</template>

<style scoped lang="scss">
  :deep(.table-tooltip) {
    max-width: 300px !important;
    max-height: 150px !important;
    overflow: auto !important;
  }

  .video_card {
    box-sizing: border-box;
    padding-top: 12px;
    display: flex;
    flex-direction: column;
    row-gap: 5px;

    .header {
      display: flex;
      justify-content: space-between;

      .btn_group {
        display: flex;
        column-gap: 5px;
      }

      .search {
        display: flex;
        column-gap: 5px;

        :deep(.el-input) {
          width: 120px;
        }
      }
    }

    .table {
      max-height: calc(100% - 80px);
    }

    .pagination {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
